(* open IntInf; *)

fun read file =
    let
        val inStream = TextIO.openIn file
    in
        (* TextIO.inputAll returns a TextIO.vector, which is a string. *)
        TextIO.inputAll inStream
    end;


fun count_increases [] = 0
  | count_increases [n] = 0
  | count_increases measurements =
    let
        val (first_measurement::rest_measurements) = measurements;

        fun iter (remaining, previous, accumulated) =
            if List.null remaining
            then
                accumulated
            else
                let
                    val (current::rest) = remaining;
                in
                    if current > previous
                    then
                        iter (rest, current, accumulated + 1)
                    else
                        iter (rest, current, accumulated)
                end
    in
        iter (rest_measurements, first_measurement, 0)
    end;


fun sliding_window_values nil window_size = []
  | sliding_window_values measurements window_size =
    let
        fun calc_window (nil, window_size, sum) = sum
          | calc_window ((m::ms), window_size, sum) =
            if window_size = 0
            then sum
            else calc_window (ms, window_size - 1, sum + m);

        fun iter nil = []
          | iter (measurements as (m::ms)) =
            (calc_window (measurements, window_size, 0)) :: (iter ms);
    in
        iter measurements
    end;


val str = read "input";
val lines = String.tokens (fn c => c = #"\n") str;
val measurements = map (fn num_as_str =>
                           case Int.fromString num_as_str of
                               SOME number => number
                             | NONE =>
                               raise Fail "encountered a non-int string")
                       lines;

count_increases (sliding_window_values measurements 3);
